package io.webchat.renthouse.services.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.webchat.renthouse.mapper.HouseImageMapper;
import io.webchat.renthouse.mapper.HouseMapper;
import io.webchat.renthouse.pojo.House;

import io.webchat.renthouse.services.IHouseService;

import io.webchat.renthouse.vo.AddHouse;
import io.webchat.renthouse.vo.HouseVo;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;


@Service
public class HouseServiceImpl implements IHouseService {

	@Autowired
	HouseMapper houseMapper;

	@Autowired
	HouseImageMapper houseImageMapper;



	@Override
	public Integer addNewHouse(House house) {

		return houseMapper.addNewHouse(house);
	}

	@Override
	public PageInfo<House>  selectHouse(HouseVo houseVo) {
		PageHelper.startPage(houseVo.getPageNum(), houseVo.getPageSize());
		List<House> houseList = houseMapper.selectHousePage(houseVo);

		List<AddHouse> addHouseList = new ArrayList<>();
		for (House house:houseList){
			AddHouse addHouse = new AddHouse();
			BeanUtils.copyProperties(house,addHouse);
			List<String> houseImages = houseImageMapper.selectByHouseIdAndType(house.getId(), 1);
			if(!CollectionUtils.isEmpty(houseImages)){
				addHouse.setHouseImage(houseImages.get(0));
			}
			List<String> houseDetailsImgList = houseImageMapper.selectByHouseIdAndType(house.getId(), 2);
			if(!CollectionUtils.isEmpty(houseDetailsImgList)){
				String houseDetailsImg = String.join(",", houseDetailsImgList);
				addHouse.setHouseDetailsImg(houseDetailsImg);
			}

			addHouseList.add(addHouse);
		}
		return new PageInfo<House>(houseList);
	}

}
